package com.xuyixuan.rabbitmq_test;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Producer {

    private static final String RABBITMQ_HOST = "your-rabbitmq-host"; // 替换为你的 RabbitMQ 主机地址
    private static final int RABBITMQ_PORT = 5672;
    private static final String RABBITMQ_USERNAME = "your-username"; // 替换为你的用户名
    private static final String RABBITMQ_PASSWORD = "your-password"; // 替换为你的密码
    private static final String RABBITMQ_VHOST = "your-vhost";       // 替换为你的 Vhost
    private static final String QUEUE_NAME = "order_queue";          // 替换为你的队列名称

    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(RABBITMQ_HOST);
        factory.setPort(RABBITMQ_PORT);
        factory.setUsername(RABBITMQ_USERNAME);
        factory.setPassword(RABBITMQ_PASSWORD);
        factory.setVirtualHost(RABBITMQ_VHOST);

        // 创建连接和通道
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        // 模拟高并发发送订单消息
        ExecutorService executorService = Executors.newFixedThreadPool(10); // 使用 10 个线程模拟高并发
        for (int i = 0; i < 1000; i++) { // 发送 1000 条订单消息
            int finalI = i;
            executorService.submit(() -> {
                try {
                    sendOrderMessage(channel, finalI);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }

        executorService.shutdown();
        try {
            connection.close();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }

    private static void sendOrderMessage(Channel channel, int i) throws IOException {
        String orderId = "order_" + i;
        String userId = "user_" + (i % 10); // 模拟 10 个用户
        String productId = "product_" + (i % 5); // 模拟 5 个商品
        int quantity = i % 10 + 1; // 模拟 1-10 的购买数量

        String message = String.format("{\"order_id\": \"%s\", \"user_id\": \"%s\", \"product_id\": \"%s\", \"quantity\": %d}",
                orderId, userId, productId, quantity);

        // 发送消息
        channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
        System.out.println("发送订单消息: " + message);
    }
}